package com.wqiuqiu.gulimall.auth.web;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.wqiuqiu.common.R;
import com.wqiuqiu.common.constant.RedisConstant;
import com.wqiuqiu.common.excption.BizCodeEnume;
import com.wqiuqiu.common.to.login.AccountTo;
import com.wqiuqiu.common.to.login.MemberResponseTo;
import com.wqiuqiu.common.to.thridservice.Oauth2To;
import com.wqiuqiu.common.utils.HttpUtils;
import com.wqiuqiu.gulimall.auth.feign.MemberFeignService;
import com.wqiuqiu.gulimall.auth.vo.Auth2Vo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;

@Slf4j
@Validated
@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/auth2login/gitee")
    public String giteeLogin(@RequestParam("code") String code, HttpSession session) throws Exception {
        // 获取access_token
        String client_secret = "4ff63ab0294d56491740c6ed8350e81a95da114bdaadf2124e50afc48c8e11a4";
        String client_id = "1db7f4e7b3304a363c875d1df29b1b33f482da41fc0609d7e13db3215948ce32";
        String redirect_uri = "http://auth.gulimall.com/login/auth2login/gitee";
        HashMap<String, String> header = new HashMap<>();
        HashMap<String, String> querys = new HashMap<>();
        HashMap<String, String> bodys = new HashMap<>();
        bodys.put("grant_type", "authorization_code");
        bodys.put("code", code);
        bodys.put("client_id", client_id);
        bodys.put("client_secret", client_secret);
        bodys.put("redirect_uri", redirect_uri);
        HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", header, querys, bodys);

        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            String jsonString = EntityUtils.toString(entity);
            Auth2Vo auth2Vo = JSON.parseObject(jsonString, Auth2Vo.class);
            System.out.println(auth2Vo.getAccess_token());
            //获取用户的第三方平台信息 判断该用户是否在本网站注册过，如果没有需要自动注册

            querys.put("access_token", auth2Vo.getAccess_token());
            response = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", header, querys);
            if (response.getStatusLine().getStatusCode() == 200) {
                //获取gitee的userId
                entity = response.getEntity();
                String string = EntityUtils.toString(entity);
                JSONObject jsonObject = JSON.parseObject(string);
                Oauth2To oauth2To = new Oauth2To();
                oauth2To.setEmail(jsonObject.getString("email"));
                oauth2To.setId(jsonObject.getString("id"));
                oauth2To.setLogin(jsonObject.getString("login"));
                oauth2To.setName(jsonObject.getString("name"));
                R r = null;
                try {
                    r = memberFeignService.oauth2Login(oauth2To);
                }catch (Exception e){
                    log.error("登录失败。。。",e.getMessage());
                    if (r == null){
                        return "redirect:http://auth.gulimall.com/login.html";
                    }
                }
                if (r.getCode() == 0) {
                    MemberResponseTo data = r.getData(new TypeReference<MemberResponseTo>() {
                    });
                    //给页面传递数据 这里有序列化的问题
                    session.setAttribute(RedisConstant.SESSIONNAME,data);

                    //TODO 登录失败，返回页面提示信息
                    return "redirect:http://gulimall.com";

                } else {
                    return "redirect:http://auth.gulimall.com/login.html";
                }
            } else {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        } else {
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }

    @PostMapping("/gulimall")
    public String gulimallLogin(@Valid AccountTo to, HttpSession session, RedirectAttributes redirectAttributes){
        //TODO 这里只对数据进行非空校验，而不进行其他格式检查，直接拿去和数据库中比对
        R r = null;
        try {
            r = memberFeignService.gulimallLogin(to);
        }catch (Exception e){
            if (r == null){
                return "redirect:http://auth.gulimall.com/login.html";
            }
        }
        if (r.getCode() == 0){
            MemberResponseTo data = r.getData(new TypeReference<MemberResponseTo>() {
            });
            session.setAttribute(RedisConstant.SESSIONNAME,data);
            return "redirect:http://gulimall.com";
        }else {
            HashMap<String,String> map = new HashMap<>();
            if (r.getCode() == BizCodeEnume.USER_NAME_EXCEPTION.getCode()){
                map.put("user",BizCodeEnume.USER_NAME_EXCEPTION.getMessage());
            }
            if (r.getCode() == BizCodeEnume.USER_PASSWORD_EXCEPTION.getCode()){
                map.put("password",BizCodeEnume.USER_PASSWORD_EXCEPTION.getMessage());
            }
            redirectAttributes.addFlashAttribute("errors",map);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
